package com.luboyan.CBillbill.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.luboyan.CBillbill.exception.ConditionException;
import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "jwt.token")
public class JwtHelper {

    private static long tokenExpiration = 4320; //有效时间,单位分钟
    private static long RefreshTokenExpiration = 10080; //有效时间,单位分钟
    private static String issuer = "luboyan";
    private static String tokenSignKey = "QmvsUiugzXHbe6cIu+cHYsDZvjpwkf0C"; //签名密钥

    /**
     * 生成token字符串
     */
    public static String createToken(Long userId) {
        String token = Jwts.builder()
                .setSubject("JWT-AUTH") //主题
                .setIssuer(issuer)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration * 1000 * 60)) //超时时间，单位分钟
                .claim("userId", userId) //内容
                .setId(String.valueOf(userId)) //唯一标识
                .signWith(SignatureAlgorithm.HS512, tokenSignKey) //获取签名密钥，采用HS512算法进行签名加密
                .compact();
        return token;
    }

    /**
     * 验证token
     */
    public static Long verifyToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        }catch (ExpiredJwtException e) {
            throw new ConditionException("511", "token过期！");
        }catch (Exception e){
            throw new ConditionException("非法用户token！");
        }
    }


    /**
     * 验证reToken
     */
    public static Long verifyReToken(String reToken) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(reToken);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        }catch (ExpiredJwtException e) {
            throw new ConditionException("512", "reToken过期！");
        }catch (Exception e){
            throw new ConditionException("非法用户token！");
        }
    }


    public static void main(String[] args) {
        byte[] keyBytes = new byte[24];
        new SecureRandom().nextBytes(keyBytes);
        String secretKey = Base64.getEncoder().encodeToString(keyBytes);
        System.out.println(secretKey);
    }

    public static String createRefreshToken(Long userId) {
        return Jwts.builder()
                .setSubject("JWT-AUTH") //主题
                .setIssuer(issuer)
                .setExpiration(new Date(System.currentTimeMillis() + RefreshTokenExpiration * 1000 * 60)) //超时时间，单位分钟
                .claim("userId", userId) //内容
                .setId(String.valueOf(userId)) //唯一标识
                .signWith(SignatureAlgorithm.HS512, tokenSignKey) //获取签名密钥，采用HS512算法进行签名加密
                .compact();
    }
}
